#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: response.py
@contact: zwb15083976291@163.com
@time: 2021/10/09
"""
import json
from enum import Enum

from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from rest_framework.response import Response


class CommonAPIResponseStatus(Enum):
    """
     后端返回响应状态码
     """
    FAILURE = (-1, "操作失败")
    OK = (200, "OK")
    BAD_REQUEST = (400, "参数不合法")
    NOT_FOUND = (404, "资源不存在")
    ACCESS_DENIED = (403, "拒绝访问")
    METHOD_NOT_ALLOWED = (405, "不支持该请求方法")
    ENUM_IS_ILLEGAL = (-4, "枚举类型不合法")
    UNSUPPORTED_MEDIA_TYPE = (415, "不支持的数据格式")
    INTERNAL_SERVER_ERROR = (500, "服务异常")
    SERVICE_UNAVAILABLE = (503, "服务正忙,请稍候再试")
    TOKEN_ERROR = (50008, "token错误")
    TOKEN_EXPIRES = (50014, "token过期")
    OTHER_CLIENTS_LOGGED = (50012, "其他客户端以登录")
    # 限流
    TOO_MANY_REQUESTS = (429, "你当前请求次数太多,请稍候再试")


def response_data(status: "CommonAPIResponseStatus" = CommonAPIResponseStatus.OK, data: dict = '',
                  message: "str:hint for code" = '', ):
    api_data = dict(zip(["code", "message"], status.value))
    if message:
        api_data['message'] = message
    api_data.update(data=data)
    return api_data


class CommonResponse(Response):
    def __init__(self, status: "CommonAPIResponseStatus" = CommonAPIResponseStatus.OK, data: dict = '',
                 message: "str:hint for code" = '',
                 template_name=None, headers=None,
                 exception=False, content_type=None):
        api_data = dict(zip(["code", "message"], status.value))
        if message:
            api_data['message'] = message
        api_data.update(data=data)
        super().__init__(data=api_data, template_name=template_name, headers=headers, exception=exception,
                         content_type=content_type)
